<?php
class stYoutubeToolboxplaylist_model extends stmodel_2_1{

    public function __construct($config) {
        parent::__construct ( $config );
        $this->setTableName($this->prefix.'st_youtubeplaylist');
        $this->setPrimaryKey('id');
    }    
        
    public function savestYoutubeToolboxPlayList($playlistListFeed) {
        $time = date_i18n('Y-m-d H:i:s');
        $dataInsert = array();
        $dataUpdate = array();
        $i=0;
        $user_id = $playlistListFeed['user_id'];
        $playlistListFeed = $playlistListFeed['playlist_entry'];
        foreach ($playlistListFeed as $playlistListEntry) {
            $id = $this->getPlayListId($playlistListEntry->title->text);
            if($id){
                $dataUpdate[$i]['id'] = $id;
                $dataUpdate[$i]['user_id'] = $user_id;
                $dataUpdate[$i]['playlist_id'] = $playlistListEntry->playlistId->text;
                $dataUpdate[$i]['name'] = $playlistListEntry->title->text;
                $dataUpdate[$i]['youtube_user'] = basename($this->option['youtube_channel']);
            }else{
                $dataInsert[$i]['id'] = 'NULL';
                $dataUpdate[$i]['user_id'] = $user_id;
                $dataInsert[$i]['cdate'] = $time;
                $dataInsert[$i]['playlist_id'] = $playlistListEntry->playlistId->text;
                $dataInsert[$i]['name'] = $playlistListEntry->title->text;
                $dataInsert[$i]['youtube_user'] = basename($this->option['youtube_channel']);
            }
            
            $i++;
        }
        $this->inserRecords($dataInsert);
        $this->updateRecords($dataUpdate);
    }

    public function inserRecords($data = '', $where = ''){
        if(count($data)>0){
            $query = "INSERT INTO $this->_tableName
                    ( id, playlist_id, name, youtube_user, cdate )
                    VALUES
                    ";
            $query1 = array();
            foreach ($data as $value) {
                $query1[] = $this->prepare("(%d, %s, %s, %s, %s)",
                            $value['id'], $value['playlist_id'], $value['name'], $value['youtube_user'], $value['cdate']);
            }
            $query1 = implode(', ', $query1);
            $query .= ' '.$query1;
            return $this->query( $query );
        }
        return false;
    }

    public function updateRecords($data = '', $where = ''){
        foreach ($data as $value) {
            $where = array($this->_primaryKey => intval($value[$this->_primaryKey]));
            $this->update($this->_tableName, $value, $where);
        }
    }

    public function getPlayListId($name){
        $query = "SELECT id
        FROM $this->_tableName
        WHERE name like('$name')
        ";
        $result = $this->get_var($query);
        return $result;
    }
}